var express = require('express');
var router = express.Router();
var { DingDanLieBiaoMedol } = require('../model/model')
let AlipaySdk = require("alipay-sdk").default;
let AlipaySdkForm = require("alipay-sdk/lib/form").default;

// 获取订单列表
router.get('/getDD', async (req, res) => {
  let { state } = req.query
  let arr = [{}]
  if (state) {
    arr.push({ state })
  }
  let data = await DingDanLieBiaoMedol.find({ $and: arr })
  res.send({
    data
  })
})

// 修改状态
router.put('/updateDD', async (req, res) => {
  let { _id, state } = req.body
  await DingDanLieBiaoMedol.updateOne({ _id }, { state })
  res.send({
    code: 200,
    msg: '修改成功'
  })
})

// 删除订单
router.delete('/deleteDD', async (req, res) => {
  let { _id } = req.query
  await DingDanLieBiaoMedol.deleteOne({ _id })
  res.send({
    code: 200,
    msg: '删除成功'
  })
})

// 支付宝沙箱支付订单
router.post('/alipay', async (req, res) => {
  let {num,title,_id} = req.body
  await DingDanLieBiaoMedol.updateOne({ _id }, { state:"待收货" })
  const alipaySdk = new AlipaySdk({
    appId: '9021000141673604',
    gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
    privateKey: "MIIEpAIBAAKCAQEAq8Gco+koGrZ9HxGnDPK3T2a+DycAVWmMxSf88bvdiEkBoTcn3XG9ps/N6k6u/rKelZGuCOxA47I//ujQanS1qpC1vBSusH9QgmkoSBrCbBFhYF5o9C+VS+tspzIwhChW4RWDPE+0Lyu7jUsfwKhsow1Gzm+AZE/JBuBJCy5eliWNyzTqsu5PttHmQFVdX0WAMUgpaDqfMWKduW8FcbYsUj61cK71SEFrOdApIYiPARf5DcqgTuVRu/SydS2bmbNk67kNbZxchtWQ1CvBgFtVmQAICgfQRUAbOR1F66xtU9vHl2+G5JO+ucFvi9pM2kkdvN/cCqt3kZ1LOsO8Hf70fwIDAQABAoIBAFgYEA2KMwWwf/CFj1b2zsqs+eKvsF4eqxMcdYJPR0r1lx5nOc0833dFsmnxPZRpbSlt9QOimY2wCV7nbq6LefooCu6S9R6Vzmd1JDIHd50SNQ3GnrJQDZVJBQuklH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uyr8xUjeAf1vU+ZPxsb2HeEMRsQ==",
    alipayPublicKey: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg99NhY1N4lUWPhP7uSdl4RPCBP8msGOaxJl3jYHdYI2LIDF5191WnoONMY8/02UdbafLz8118tXFBUmy6s7H6PEaYxUDV46OIheXX4kBQpOYAy4N5ZWbzd00ygh3m4aA7PHBL7TMUge5J++8mRvg1830HJg8p7v4Wj9USTMJfY5KeBtcc9/GIOL+G0Yru6DA741zYQsOg4GjuaLjcE8rGP6nNQHdKO7hFORpkGKMgLMv0mKlOj0fyWRcGR0cyb47zUzIi8a93dPg2F5d3rWybI9VxsTdFAm7q2KC9GLzkvlIGScRHC8acGR8V2mEs0ydb5jcw4q10YMxv2GrSHLRewIDAQAB",
    signType: "RSA2",
  })

  let formData = new AlipaySdkForm()
  formData.addField('returnUrl', 'http://localhost:5173/yifukuan')
  formData.addField('bizContent', {
    outTradeNo: Date.now(),
    productCode: 'FAST_INSTANT_TRADE_PAY',
    totalAmount: num,
    subject: title,
    body: "商品详情"
  })


  let result = await alipaySdk.exec(
    'alipay.trade.wap.pay',
    // 'alipay.trade.page.pay',
    {},
    { formData: formData }
  )
  res.send(result)
})


// 查看订单详情
router.get('/getXq', async (req, res) => {
  let { _id } = req.query
  let result = await DingDanLieBiaoMedol.findOne({ _id })
  res.send({
    code: 200,
    msg: '查询成功',
    data: result
  })
})

module.exports = router;